using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using ServiceControllerApp.Models;
using ServiceControllerApp.SqlImporter;
using System.Globalization;
using System.Windows.Data;

namespace ServiceControllerApp
{
    public partial class MainWindow : Window
    {
        private AppConfig appConfig;
        private List<string> serviceNames = new List<string>();

        public ObservableCollection<ServiceItem> Services { get; set; }

        WaitWindow? waitWindow;

        public MainWindow()
        {
            InitializeComponent();
            
            // 添加Loaded事件处理，确保UI完全加载后再进行初始化
            this.Loaded += MainWindow_Loaded;
            
            // 加载配置
            appConfig = AppConfig.Load();
            serviceNames = appConfig.ServiceNames.ToList();
            
            InitializePlaceholders();
            
            Services = new ObservableCollection<ServiceItem>();
            ServiceListView.ItemsSource = Services;
            
            UpdateServiceStatusAsync();
            UpdateListViewHeight();

            try
            {
                string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                this.Title = $"{this.Title} v{version}";
            }
            catch (Exception)
            {
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保默认显示服务管理页面
            ShowPage("Service");
        }

        private void UpdateListViewHeight()
        {
            // 在现代化界面中，ListView在卡片内，不需要严格控制高度
            // 让它自然适应内容
            int itemCount = serviceNames.Count;
            
            if (itemCount == 0)
            {
                ServiceListView.Height = 120;
                return;
            }
            
            double headerHeight = 30;
            double itemHeight = 50; 
            double listViewBorderAndPadding = 15;
            double calculatedHeight = headerHeight + (itemCount * itemHeight) + listViewBorderAndPadding;
            
            // 在现代化布局中允许更大的高度范围
            double finalHeight = Math.Max(120, Math.Min(600, calculatedHeight));
            
            ServiceListView.Height = finalHeight;
            
            System.Diagnostics.Debug.WriteLine($"现代化界面ListView高度: 服务数量={itemCount}, 最终高度={finalHeight:F0}");
        }

        #region 导航事件处理
        private void ServiceTab_Checked(object sender, RoutedEventArgs e)
        {
            // 确保在UI完全加载后再调用
            if (IsLoaded)
                ShowPage("Service");
        }

        private void DatabaseTab_Checked(object sender, RoutedEventArgs e)
        {
            // 确保在UI完全加载后再调用
            if (IsLoaded)
                ShowPage("Database");
        }

        private void SettingsTab_Checked(object sender, RoutedEventArgs e)
        {
            // 确保在UI完全加载后再调用
            if (IsLoaded)
                ShowPage("Settings");
        }

        private void ToolsTab_Checked(object sender, RoutedEventArgs e)
        {
            // 确保在UI完全加载后再调用
            if (IsLoaded)
                ShowPage("Tools");
        }

        private void ShowPage(string pageName)
        {
            try
            {
                // 确保页面元素已初始化
                if (ServicePage == null || DatabasePage == null || ToolsPage == null || SettingsPage == null)
                {
                    System.Diagnostics.Debug.WriteLine("页面元素尚未初始化");
                    return;
                }

                // 隐藏所有页面
                ServicePage.Visibility = Visibility.Collapsed;
                DatabasePage.Visibility = Visibility.Collapsed;
                ToolsPage.Visibility = Visibility.Collapsed;
                SettingsPage.Visibility = Visibility.Collapsed;

                // 显示指定页面
                switch (pageName)
                {
                    case "Service":
                        ServicePage.Visibility = Visibility.Visible;
                        break;
                    case "Database":
                        DatabasePage.Visibility = Visibility.Visible;
                        break;
                    case "Tools":
                        ToolsPage.Visibility = Visibility.Visible;
                        break;
                    case "Settings":
                        SettingsPage.Visibility = Visibility.Visible;
                        break;
                    default:
                        // 默认显示服务页面
                        ServicePage.Visibility = Visibility.Visible;
                        break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"ShowPage方法异常: {ex.Message}");
                MessageBox.Show(this, $"页面切换失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region 原有功能保持不变
        private void btnEditServices_Click(object sender, RoutedEventArgs e)
        {
            var editWindow = new ServiceEditWindow(serviceNames)
            {
                Owner = this
            };

            if (editWindow.ShowDialog() == true && editWindow.IsSaved)
            {
                serviceNames = editWindow.GetServiceNames();
                appConfig.ServiceNames = serviceNames;
                appConfig.Save();
                
                UpdateServiceStatusAsync();
                UpdateListViewHeight();
            }
        }

        private void InitializePlaceholders()
        {
            txtHost.Foreground = Brushes.Gray;
            txtHost.Text = "请输入数据库主机";

            txtPort.Foreground = Brushes.Gray;
            txtPort.Text = "请输入数据库端口";

            txtDatabase.Foreground = Brushes.Gray;
            txtDatabase.Text = "请输入数据库名称 (默认 hs_db)";

            txtUser.Foreground = Brushes.Gray;
            txtUser.Text = "请输入数据库用户名";
        }

        private async void btnStart_Click(object sender, RoutedEventArgs e)
        {
            foreach (var serviceName in serviceNames)
            {
                await StartServiceAsync(serviceName);
            }
            await UpdateServiceStatusAsync();
        }

        private async void btnStop_Click(object sender, RoutedEventArgs e)
        {
            foreach (var serviceName in serviceNames)
            {
                await StopServiceAsync(serviceName);
            }
            await UpdateServiceStatusAsync();
        }

        private async void ServiceControl_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null)
            {
                var serviceItem = button.DataContext as ServiceItem;
                if (serviceItem != null)
                {
                    if (serviceItem.Status == "Running")
                    {
                        await StopServiceAsync(serviceItem.ServiceName);
                    }
                    else if (serviceItem.Status == "Stopped")
                    {
                        await StartServiceAsync(serviceItem.ServiceName);
                    }
                    await UpdateServiceStatusAsync();
                }
            }
        }

        private async Task StartServiceAsync(string serviceName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(serviceName))
                {
                    System.Diagnostics.Debug.WriteLine("启动服务失败: 服务名称为空");
                    return;
                }

                await Task.Run(() =>
                {
                    try
                    {
                        using (var service = new ServiceController(serviceName))
                        {
                            if (service.Status == ServiceControllerStatus.Stopped)
                            {
                                service.Start();
                                service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                                System.Diagnostics.Debug.WriteLine($"服务 {serviceName} 启动成功");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine($"服务 {serviceName} 已经在运行，状态: {service.Status}");
                            }
                        }
                    }
                    catch (System.ComponentModel.Win32Exception ex)
                    {
                        if (ex.NativeErrorCode == 5) // ERROR_ACCESS_DENIED
                        {
                            System.Diagnostics.Debug.WriteLine($"启动服务 {serviceName} 失败: 权限不足，需要管理员权限");
                            MessageBox.Show(Application.Current.MainWindow, 
                                $"启动服务 {serviceName} 失败: 权限不足\n请以管理员身份运行此程序", 
                                "权限错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"启动服务 {serviceName} 失败: {ex.Message} (错误代码: {ex.NativeErrorCode})");
                            MessageBox.Show(Application.Current.MainWindow, 
                                $"启动服务 {serviceName} 失败: {ex.Message}", 
                                "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    catch (InvalidOperationException ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"启动服务 {serviceName} 失败: 服务不存在或无效操作 - {ex.Message}");
                        MessageBox.Show(Application.Current.MainWindow, 
                            $"启动服务 {serviceName} 失败: 服务不存在或无效操作", 
                            "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"启动服务 {serviceName} 时发生未知错误: {ex.Message}");
                        MessageBox.Show(Application.Current.MainWindow, 
                            $"启动服务 {serviceName} 失败: {ex.Message}", 
                            "未知错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"StartServiceAsync 外层异常: {ex.Message}");
            }
        }

        private async Task StopServiceAsync(string serviceName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(serviceName))
                {
                    System.Diagnostics.Debug.WriteLine("停止服务失败: 服务名称为空");
                    return;
                }

                await Task.Run(() =>
                {
                    try
                    {
                        using (var service = new ServiceController(serviceName))
                        {
                            if (service.Status == ServiceControllerStatus.Running)
                            {
                                service.Stop();
                                service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
                                System.Diagnostics.Debug.WriteLine($"服务 {serviceName} 停止成功");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine($"服务 {serviceName} 已经停止，状态: {service.Status}");
                            }
                        }
                    }
                    catch (System.ComponentModel.Win32Exception ex)
                    {
                        if (ex.NativeErrorCode == 5) // ERROR_ACCESS_DENIED
                        {
                            System.Diagnostics.Debug.WriteLine($"停止服务 {serviceName} 失败: 权限不足，需要管理员权限");
                            MessageBox.Show(Application.Current.MainWindow, 
                                $"停止服务 {serviceName} 失败: 权限不足\n请以管理员身份运行此程序", 
                                "权限错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"停止服务 {serviceName} 失败: {ex.Message} (错误代码: {ex.NativeErrorCode})");
                            MessageBox.Show(Application.Current.MainWindow, 
                                $"停止服务 {serviceName} 失败: {ex.Message}", 
                                "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    catch (InvalidOperationException ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"停止服务 {serviceName} 失败: 服务不存在或无效操作 - {ex.Message}");
                        MessageBox.Show(Application.Current.MainWindow, 
                            $"停止服务 {serviceName} 失败: 服务不存在或无效操作", 
                            "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"停止服务 {serviceName} 时发生未知错误: {ex.Message}");
                        MessageBox.Show(Application.Current.MainWindow, 
                            $"停止服务 {serviceName} 失败: {ex.Message}", 
                            "未知错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"StopServiceAsync 外层异常: {ex.Message}");
            }
        }

        private async Task UpdateServiceStatusAsync()
        {
            Services.Clear();
            foreach (var serviceName in serviceNames)
            {
                var status = await GetServiceStatusAsync(serviceName);
                var buttonContent = status == "Running" ? "停止" : "启动";
                Services.Add(new ServiceItem
                {
                    ServiceName = serviceName,
                    Status = status,
                    ButtonContent = buttonContent
                });
            }
            
            UpdateListViewHeight();
        }

        private async Task<string> GetServiceStatusAsync(string serviceName)
        {
            try
            {
                // 检查服务名称是否为空
                if (string.IsNullOrWhiteSpace(serviceName))
                {
                    return "服务名称无效";
                }

                return await Task.Run(() =>
                {
                    try
                    {
                        using (var service = new ServiceController(serviceName))
                        {
                            // 先检查服务是否存在
                            var status = service.Status;
                            return status.ToString();
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        return "服务未安装";
                    }
                    catch (System.ComponentModel.Win32Exception ex)
                    {
                        // 权限不足或其他Windows API错误
                        if (ex.NativeErrorCode == 5) // ERROR_ACCESS_DENIED
                        {
                            return "权限不足";
                        }
                        else if (ex.NativeErrorCode == 1060) // ERROR_SERVICE_DOES_NOT_EXIST
                        {
                            return "服务不存在";
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"服务 {serviceName} 访问错误: {ex.Message} (错误代码: {ex.NativeErrorCode})");
                            return $"访问错误({ex.NativeErrorCode})";
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"获取服务 {serviceName} 状态时发生未知错误: {ex.Message}");
                        return "状态未知";
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"GetServiceStatusAsync 外层异常: {ex.Message}");
                return "获取失败";
            }
        }

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null && textBox.Foreground == Brushes.Gray && textBox.Text == textBox.Tag?.ToString())
            {
                textBox.Text = "";
                textBox.Foreground = Brushes.Black;
            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null && string.IsNullOrWhiteSpace(textBox.Text))
            {
                string hintText = textBox.Tag?.ToString();
                textBox.Text = hintText;
                textBox.Foreground = Brushes.Gray;
            }
        }

        private void btnTestConnection_Click(object sender, RoutedEventArgs e)
        {
            string database = txtDatabase.Text;
            string username = txtUser.Text;
            string password = txtPassword.Password;
            string serverHost = txtHost.Text;
            string port = txtPort.Text;

            string connectionString = $"Server={serverHost};Port={port};User Id={username};Password={password};CharSet=utf8mb4;";

            try
            {
                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    MessageBox.Show(this, "🎉 数据库连接成功！", "连接测试", MessageBoxButton.OK, MessageBoxImage.Information);

                    string query = $"SHOW DATABASES LIKE '{database}'";
                    using (var cmd = new MySqlCommand(query, connection))
                    {
                        var result = cmd.ExecuteScalar();
                        if (result != null)
                        {
                            MessageBox.Show(this, $"✅ 数据库 {database} 存在！", "连接测试", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            MessageBox.Show(this, $"⚠️ 数据库 {database} 不存在！\n请选择SQL初始文件并导入数据库！", "连接测试", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"❌ 数据库连接失败：\n{ex.Message}", "连接测试", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task<ImportResult> ImportDatabaseAsync(string sqlFilePath = "bak_db.sql")
        {
            if (!File.Exists(sqlFilePath))
            {
                return new ImportResult { Success = false, ErrorMessage = "SQL 文件不存在。" };
            }

            string databaseName = txtDatabase.Text;
            string username = txtUser.Text;
            string password = txtPassword.Password;
            string serverHost = txtHost.Text;
            string port = txtPort.Text;

            try
            {
                var sqlBackupImporter = new SqlBackupImporter(sqlFilePath, databaseName, username, password, serverHost, port);
                ImportResult result = await sqlBackupImporter.ImportSqlBackup();
                return result;
            }
            catch (Exception ex)
            {
                return new ImportResult
                {
                    Success = false,
                    ErrorMessage = $"错误: {ex.Message}"
                };
            }
        }

        private async void btnImport_Click(object sender, RoutedEventArgs e)
        {
            string appDirectory = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            string defaultFilePath = System.IO.Path.Combine(appDirectory, "bak_db.sql");

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "SQL Files (*.sql)|*.sql|All Files (*.*)|*.*";
            openFileDialog.InitialDirectory = appDirectory;
            openFileDialog.FileName = defaultFilePath;

            string selectedFile = defaultFilePath;
            if (openFileDialog.ShowDialog() == true)
            {
                selectedFile = openFileDialog.FileName;
                MessageBox.Show(this, $"📁 您选择的文件是：\n{selectedFile}", "文件选择", MessageBoxButton.OK, MessageBoxImage.Information);
            }

            if (waitWindow == null)
                waitWindow = new WaitWindow();
            waitWindow.IsCanClose = false;
            waitWindow.Owner = this;
            waitWindow.Show();

            ImportResult result = await ImportDatabaseAsync(selectedFile);
            waitWindow.Hide();
            
            if (result.Success)
            {
                MessageBox.Show(this, "🎉 导入成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(this, $"❌ 导入失败:\n{result.ErrorMessage}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region 工具页面功能
        private void btnOpenObserve_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string url = txtOpenObserveUrl.Text.Trim();
                if (string.IsNullOrEmpty(url))
                {
                    MessageBox.Show(this, "请输入 OpenObserve 地址", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 确保URL格式正确
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "http://" + url;
                }

                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                });

                System.Diagnostics.Debug.WriteLine($"已打开 OpenObserve: {url}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"打开 OpenObserve 失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOpenObserveDashboard_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string baseUrl = txtOpenObserveUrl.Text.Trim();
                if (string.IsNullOrEmpty(baseUrl))
                {
                    MessageBox.Show(this, "请输入 OpenObserve 地址", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 确保URL格式正确
                if (!baseUrl.StartsWith("http://") && !baseUrl.StartsWith("https://"))
                {
                    baseUrl = "http://" + baseUrl;
                }

                // 跳转到仪表板页面
                string dashboardUrl = baseUrl.TrimEnd('/') + "/web/dashboard";

                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = dashboardUrl,
                    UseShellExecute = true
                });

                System.Diagnostics.Debug.WriteLine($"已打开 OpenObserve 仪表板: {dashboardUrl}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"打开 OpenObserve 仪表板失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOpenEventViewer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "eventvwr.msc",
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"打开事件查看器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOpenServicesManager_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "services.msc",
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"打开服务管理器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOpenTaskManager_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "taskmgr.exe",
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"打开任务管理器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion
    }

    // 状态到背景颜色的转换器
    public class StatusToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string status)
            {
                switch (status)
                {
                    case "Running":
                        return new SolidColorBrush(Color.FromRgb(232, 245, 233));     // 淡绿色背景 - 运行中
                    case "Stopped":
                        return new SolidColorBrush(Color.FromRgb(255, 235, 238));     // 淡红色背景 - 已停止
                    case "权限不足":
                    case "访问错误":
                        return new SolidColorBrush(Color.FromRgb(255, 243, 224));     // 淡橙色背景 - 权限/访问问题
                    case "服务不存在":
                    case "服务未安装":
                    case "状态未知":
                    case "获取失败":
                        return new SolidColorBrush(Color.FromRgb(245, 245, 245));     // 浅灰色背景 - 错误/未知
                    default:
                        return new SolidColorBrush(Color.FromRgb(255, 255, 255));     // 白色 - 默认
                }
            }
            return new SolidColorBrush(Color.FromRgb(255, 255, 255));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    // 状态到文字颜色的转换器
    public class StatusToTextColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string status)
            {
                switch (status)
                {
                    case "Running":
                        return new SolidColorBrush(Color.FromRgb(46, 125, 50));       // 深绿色 - 更清晰但不刺眼
                    case "Stopped":
                        return new SolidColorBrush(Color.FromRgb(198, 40, 40));       // 深红色 - 更柔和
                    case "权限不足":
                    case "访问错误":
                        return new SolidColorBrush(Color.FromRgb(239, 108, 0));       // 深橙色 - 更温和
                    case "服务不存在":
                    case "服务未安装":
                    case "状态未知":
                    case "获取失败":
                        return new SolidColorBrush(Color.FromRgb(117, 117, 117));     // 中灰色 - 更清晰
                    default:
                        return new SolidColorBrush(Color.FromRgb(33, 33, 33));        // 深色文字
                }
            }
            return new SolidColorBrush(Color.FromRgb(33, 33, 33));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
} 